package Security

import (
	"back_go/Common"
	"back_go/DAO"
	models "back_go/DAO/model"
	middleware "back_go/Middleware"
	"back_go/Response"
	"fmt"
	"log"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

type User struct {
	UserName string `json:"userName"`
	Password string `json:"password"`
}
type Token struct {
	AccessToken  string `json:"accessToken"`
	RefreshToken string `json:"refreshToken"`
	ExpiresIn    string `json:"expiresIn"`
}

// AdminLogin
/*
	@userName 用户名
	@password 密码
	@return token
*/
func AdminLogin(c *gin.Context) {
	var engine = DAO.Engine
	var User User
	var TzSysUser models.TzSysUser
	_ = c.ShouldBindJSON(&User)
	fmt.Println(User.UserName + "                     " + User.Password)

	err, _ := engine.Where("username=?", User.UserName).Get(&TzSysUser)

	if !err {
		c.JSON(http.StatusOK, Response.ResponseBody{
			Code:      "A00001",
			Msg:       "账号或密码不正确",
			Data:      nil,
			Version:   "1.0",
			Timestamp: time.Now().Unix(),
			Sign:      "",
			Success:   false,
			Fail:      true,
		})

		return
	}
	encrypt, _ := Common.AESEncrypt([]byte(User.Password))
	// 对比密码

	if TzSysUser.Password != encrypt {
		c.JSON(200, Response.ResponseBody{
			Code:      "A00001",
			Msg:       "账号或密码不正确",
			Data:      nil,
			Version:   "1.0",
			Timestamp: time.Now().Unix(),
			Sign:      "",
			Success:   false,
			Fail:      true,
		})

		return
	}
	var Token Token
	token := Common.EncodeToken(int(TzSysUser.UserId), TzSysUser.Username)
	Token.AccessToken = token
	Token.RefreshToken = token
	Token.ExpiresIn = "2592000"
	key := "auth:" + TzSysUser.Username
	cmd := middleware.RedisClient.Set(c, key, token, time.Duration(2592000)*time.Second)
	if cmd.Err() != nil {
		log.Println("Redis set error:", cmd.Err())
		c.JSON(http.StatusOK, Response.ResponseBody{
			Code:      "A00001",
			Msg:       "服务器错误",
			Data:      nil,
			Version:   "1.0",
			Timestamp: time.Now().Unix(),
			Sign:      "",
			Success:   false,
			Fail:      true,
		})
		return
	}
	c.JSON(http.StatusOK, Response.ResponseBody{
		Code:      "00000",
		Msg:       "",
		Data:      Token,
		Version:   "1.0",
		Timestamp: time.Now().Unix(),
		Sign:      "",
		Success:   true,
		Fail:      false,
	})
}

// AdminLogout
/*
	@return token
*/
func AdminLogout(c *gin.Context) {
	authHeader := c.GetHeader("Authorization")
	_, UserName, _ := Common.CodeToken(authHeader)
	middleware.RedisClient.Del(c, UserName)
	c.JSON(200, Response.ResponseBody{
		Code:      "00000",
		Msg:       "",
		Data:      nil,
		Version:   "1.0",
		Timestamp: time.Now().Unix(),
		Sign:      "",
		Success:   true,
		Fail:      false,
	})
}
